package com.bestcem.xm.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.uitls.JsonUtil;
import com.bestcem.xm.member.constant.ColumnConstant;
import com.bestcem.xm.member.dao.MemberDao;
import com.bestcem.xm.member.dao.SourceCardDao;
import com.bestcem.xm.member.entity.mysql.SourceCardDo;
import com.bestcem.xm.member.entity.pojo.MemberDO;
import com.bestcem.xm.member.grpc.service.param.ListSourceCardsParam;
import com.bestcem.xm.member.grpc.service.param.PageParam;
import com.bestcem.xm.member.mq.message.SourceCardMessage;
import com.bestcem.xm.member.service.SourceCardService;
import com.bestcem.xm.member.service.dto.PageDTO;
import com.bestcem.xm.member.service.dto.SourceCardDTO;
import com.bestcem.xm.member.service.mq.send.MemberMessageSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 来源名片服务
 * @date 2021-08-01
 */
@Slf4j
@Service("sourceCardService")
public class SourceCardServiceImpl implements SourceCardService {

    /**
     * 通用数据访问
     */
    @Resource
    private MemberDao memberDao;

    /**
     * 来源名片数据访问
     */
    @Resource
    private SourceCardDao sourceCardDao;

//    @Resource
//    private RabbitMessageSender rabbitMessageSender;
//
//    @Resource
//    private RabbitMqConstantConfig rabbitMqConstantConfig;

    @Resource
    private MemberMessageSendService memberMessageSendService;

    /**
     * 获取来源名片列表
     *
     * @param param
     * @return
     */
    @Override
    public ServiceResult<PageDTO<SourceCardDTO>> listSourceCards(ListSourceCardsParam param) {
        String orgId = param.getOrgId();
        String memberId = param.getMemberId();
        PageParam page = param.getPage();

        MemberDO member = memberDao.findById(memberId);
        if (member == null) {
            return ServiceResult.fail("联系人标识无效");
        }

        Long count = sourceCardDao.count(orgId, memberId);
        List<SourceCardDo> sourceCards = sourceCardDao.pageList(page.getPage() - 1, page.getSize(), orgId, memberId);
        List<SourceCardDTO> sourceCardDTOs = this.toSourceCardDTOs(sourceCards, member.getMemberType());
        return ServiceResult.success(PageDTO.<SourceCardDTO>builder().total(count.intValue())
                .rows(sourceCardDTOs).build());
    }

    /**
     * 类型转换
     *
     * @param sourceCards
     * @param memberType
     * @return
     */
    private List<SourceCardDTO> toSourceCardDTOs(List<SourceCardDo> sourceCards, Integer memberType) {
        if (CollectionUtils.isEmpty(sourceCards)) {
            return Collections.emptyList();
        }

        return sourceCards.stream()
                .map(sourceCard -> {
                    SourceCardDTO sourceCardDTO = this.toSourceCardDTO(sourceCard);
                    sourceCardDTO.setMType(memberType);
                    return sourceCardDTO;
                }).collect(Collectors.toList());
    }

    /**
     * 类型转换
     *
     * @param sourceCard
     * @return
     */
    private SourceCardDTO toSourceCardDTO(SourceCardDo sourceCard) {
        SourceCardDTO sourceCardDTO = new SourceCardDTO();
        if (sourceCard == null) {
            return sourceCardDTO;
        }

        JSONObject data = JsonUtil.tryConvertToJSONObject(sourceCard.getData());
        sourceCardDTO.setSerial(sourceCard.getSerial());
        sourceCardDTO.setSource(sourceCard.getSource());
        sourceCardDTO.setData(JSONObject.parseObject(sourceCard.getData()));
        sourceCardDTO.setMemberId(sourceCard.getMemberId());
        if (data != null) {
            sourceCardDTO.setName(data.getString(ColumnConstant.Member.NAME));
            sourceCardDTO.setGender(data.getString(ColumnConstant.Member.GENDER));
            sourceCardDTO.setBirthday(data.getString(ColumnConstant.Member.BIRTHDAY));
            sourceCardDTO.setAppId(data.getString(ColumnConstant.Member.APP_ID));
            sourceCardDTO.setOpenId(data.getString(ColumnConstant.Member.OPEN_ID));
            sourceCardDTO.setAlipayUserId(data.getString(ColumnConstant.Member.ALIPAY_USER_ID));
            sourceCardDTO.setMobile(data.getString(ColumnConstant.Member.MOBILE));
            sourceCardDTO.setEmail(data.getString(ColumnConstant.Member.EMAIL));
        }
        return sourceCardDTO;
    }

    @Override
    public void publishSourceCard(MemberDO newMember, Integer type) {
        SourceCardMessage message = new SourceCardMessage();
        BeanUtil.copyProperties(newMember, message);
        message.setCardSourceType(type);
//        try {
//            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppBpMemberMemberDbExchange(),
//                    rabbitMqConstantConfig.getAppBpMemberMemberDbQueue(), "member.source_card_save", message);
//        } catch (Exception e) {
//            log.error("发布来源名片失败", e);
//        }

        //stream mq /2022.05.11
        memberMessageSendService.memberDbSend(message);
    }

    @Override
    public void handleSourceCard(SourceCardMessage message) {
        // 创建名片 手工创建&编辑个人联系人只保留一张名片
        SourceCardDo card = new SourceCardDo();
        card.setMemberId(message.getId());
        card.setSource(message.getCardSourceType());
        card.setOrgId(message.getOrgId());

        //  获取该联系人的名片
        List<SourceCardDo> sourceCards = sourceCardDao.findByMid(message.getId());
        String cardNo = message.getMemberNo() + "-" + NumberUtil.decimalFormat("000", sourceCards.size() + 1);
        card.setSerial(cardNo);
        card.setData(JSONObject.toJSONString(message));
        sourceCardDao.save(card);
    }
}
